package com.ruoyi.system.utils.wechat;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.net.url.UrlBuilder;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.domain.WechatLoginBean;
import com.ruoyi.system.domain.WechatUser;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;

/**
 * @author zzxjs
 */
@Component
public class WechatUserUtil {
    private static final Log log = LogFactory.get(WechatUserUtil.class);

    @Autowired
    private RedisCache redisCache;

    @Value("${wechat.appid}")private String appid;
    @Value("${wechat.secret}")private String secret;
    @Value("${wechat.grantType}")private String grantType;
    @Value("${wechat.url}")private String url;

    public WechatUser getUserInfo(WechatLoginBean loginRequest) {
        log.info("微信登录用户信息：{}",JSONUtil.toJsonPrettyStr(loginRequest));
        //先从缓存中获取
        String key = Constants.WECHAT_CODE_OPEN_INFO + loginRequest.getUuid();
        JSONObject openInfo = redisCache.getCacheObject(key);
        if (ObjectUtil.isEmpty(openInfo)){
            openInfo = getSessionKeyOrOpenId(loginRequest.getCode());
        }
        // 获取openId && sessionKey
        String openId = openInfo.getStr("openid");
        String sessionKey = openInfo.getStr("session_key");
        if (StrUtil.isBlank(openId)){
            throw new ServiceException(openInfo.getStr("errmsg"),openInfo.getInt("errcode"));
        }
        //校验签名 小程序发送的签名signature与服务器端生成的签名signature2 = sha1(rawData + sessionKey)
//        String signature2 = DigestUtils.sha1Hex(loginRequest.getRawData().toString() + sessionKey);
//        if (!loginRequest.getSignature().equals(signature2)) {
//            throw new ServiceException("签名校验失败");
//        }
        return buildWechatUserAuthInfoDO(loginRequest, sessionKey, openId);
        // 根据openid查询用户
//        WechatUser user = wechatUserMapper.selectWechatUserList(new WechatUser() {{
//            setOpenId(openId);
//        }}).get(0);
//        if (user == null) {
//            // 用户不存在，insert用户
//            wechatUserMapper.insertWechatUser(insertOrUpdateDO);
//        } else {
//            // 已存在，更新用户的信息
//            insertOrUpdateDO.setId(user.getId());
//            wechatUserMapper.updateWechatUser(insertOrUpdateDO);
//        }
//        return insertOrUpdateDO;
    }

    public JSONObject getSessionKeyOrOpenId(String code) {
        UrlBuilder urlBuilder = UrlBuilder.of(url);
        urlBuilder.addQuery("appid", appid);
        urlBuilder.addQuery("secret", secret);
        urlBuilder.addQuery("js_code", code);
        urlBuilder.addQuery("grant_type", grantType);
        String wechatUrl = urlBuilder.toString();
        // 发送post请求读取调用微信接口获取openid用户唯一标识
        String result = HttpUtils.sendGet(wechatUrl);
        log.info("【{}】url:{},result:{}","请求微信用户信息",wechatUrl,result);
        return JSONUtil.parseObj(result);
    }


    /**
     * 解密微信用户信息
     *
     * @param loginRequest 前端传递数据
     * @param sessionKey    会话密钥
     * @return 用户信息
     */
    private WechatUser buildWechatUserAuthInfoDO(WechatLoginBean loginRequest, String sessionKey, String openId){
        WechatUser wechatUserDO = new WechatUser();
        wechatUserDO.setOpenId(openId);
        //属性赋值
        wechatUserDO.setWechatData(loginRequest.getRawData(), loginRequest.getDeptId());
        // 解密加密信息，获取unionID
        if (loginRequest.getEncryptedData() != null){
            JSONObject encryptedData = getEncryptedData(loginRequest.getEncryptedData(), sessionKey, loginRequest.getIv());
            log.info("解密后的数据：{}",encryptedData);
            if (encryptedData != null){
                wechatUserDO.setUnionId(encryptedData.getStr("unionId"));
                wechatUserDO.setMobile(encryptedData.getStr("phoneNumber"));
            }
        }
        return wechatUserDO;
    }

    private JSONObject getEncryptedData(String encryptedData, String sessionkey, String iv) {
        // 被加密的数据
        byte[] dataByte = Base64.decode(encryptedData);
        // 加密秘钥
        byte[] keyByte = Base64.decode(sessionkey);
        // 偏移量
        byte[] ivByte = Base64.decode(iv);
        try {
            // 如果密钥不足16位，那么就补足.这个if中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + 1;
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, StandardCharsets.UTF_8);
                return JSONUtil.parseObj(result);
            }
        } catch (Exception e) {
            log.error("解密加密信息报错",e);
        }
        return null;
    }
}
